import { type UserInfo, UserRole, ROLE_PERMISSIONS } from '../types/auth';

// 预定义的用户账号
const PREDEFINED_USERS = {
  '11111111111': {
    password: 'admin123',
    role: UserRole.ADMIN,
    nickname: '管理员',
    headimgurl: 'https://via.placeholder.com/100x100/07c160/ffffff?text=A',
    openid: 'admin_openid_001'
  },
  '12222222222': {
    password: 'user123',
    role: UserRole.USER,
    nickname: '普通用户',
    headimgurl: 'https://via.placeholder.com/100x100/666666/ffffff?text=U',
    openid: 'user_openid_002'
  }
};

// 手机号登录接口
export interface PhoneLoginRequest {
  phone: string;
  password: string;
}

// 手机号登录响应
export interface PhoneLoginResponse {
  success: boolean;
  message: string;
  userInfo?: UserInfo;
}

// 手机号登录
export const phoneLogin = async (phone: string, password: string): Promise<PhoneLoginResponse> => {
  // 模拟API调用延迟
  await new Promise(resolve => setTimeout(resolve, 1000));
  
  const user = PREDEFINED_USERS[phone as keyof typeof PREDEFINED_USERS];
  
  if (!user) {
    return {
      success: false,
      message: '用户不存在'
    };
  }
  
  if (user.password !== password) {
    return {
      success: false,
      message: '密码错误'
    };
  }
  
  // 构建用户信息
  const userInfo: UserInfo = {
    id: user.openid,
    openid: user.openid,
    nickname: user.nickname,
    headimgurl: user.headimgurl,
    role: user.role,
    permissions: ROLE_PERMISSIONS[user.role],
    accessToken: `phone_token_${Date.now()}`
  };
  
  return {
    success: true,
    message: '登录成功',
    userInfo
  };
};

// 验证手机号格式
export const validatePhone = (phone: string): boolean => {
  // 允许测试账号和标准手机号格式
  const testPhoneRegex = /^1[1-9]\d{9}$/;
  return testPhoneRegex.test(phone) && phone.length === 11;
};

// 验证密码格式
export const validatePassword = (password: string): boolean => {
  return password.length >= 6;
}; 